'use strict'

let { Sequelize, DataTypes } = require('sequelize');
let { database, username, password, host, dialect } = require('./config');

let sequelize = new Sequelize(database, username, password, {
    host: host,
    dialect: dialect
});

function defineModel(name, arrts) {
    let prop = {};

    prop.id = {
        type: DataTypes.BIGINT,
        primaryKey: true
    }

    for (let Key in arrts) {
        let value = arrts[Key];
        prop[Key] = value;
    }

    prop.createdAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    }

    prop.updatedAt = {
        type: DataTypes.BIGINT,
        allowNull: false
    }

    prop.version = {
        type: DataTypes.INTEGER,
        allowNull: false
    }

    prop.remarks = {
        type: DataTypes.STRING(800),
        allowNull: true
    }

    let User = sequelize.define(name, prop, {
        tableName: name,
        timestamps: false,
        hooks: {
            beforeValidate: function (obj) {
                let nw = Data.now();

                if (obj.isNewRecord) {
                    obj.createdAt = nw;
                    obj.updatedAt = nw;
                    obj.version = 0;
                } else {
                    obj.updatedAt = nw;
                    obj.version += 1;
                }
            }
        }
    })
    return User;
}

let obj = {
    sequelize,
    defineModel,
    DataTypes
}

module.exports = obj;